using Senparc.Weixin.Entities;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.Utilities.WeixinUtility;
using System;
namespace Senparc.Weixin.MP
{
	public static class ApiHandlerWapper
	{
		public static T TryCommonApi<T>(Func<string, T> fun, string accessTokenOrAppId = null, bool retryIfFaild = true) where T : WxJsonResult
		{
			string text = null;
			string text2 = null;
			if (accessTokenOrAppId == null)
			{
				text = AccessTokenContainer.GetFirstOrDefaultAppId();
				if (text == null)
				{
					throw new WeixinException("尚无已经注册的AppId，请先使用AccessTokenContainer.Register完成注册（全局执行一次即可）！");
				}
			}
			else
			{
				if (ApiUtility.IsAppId(accessTokenOrAppId))
				{
					if (!AccessTokenContainer.CheckRegistered(accessTokenOrAppId))
					{
						throw new WeixinException("此appId尚未注册，请先使用AccessTokenContainer.Register完成注册（全局执行一次即可）！");
					}
					text = accessTokenOrAppId;
				}
				else
				{
					text2 = accessTokenOrAppId;
				}
			}
			T result = default(T);
			try
			{
				if (text2 == null)
				{
					AccessTokenResult tokenResult = AccessTokenContainer.GetTokenResult(text, false);
					text2 = tokenResult.access_token;
				}
				result = fun(text2);
			}
			catch (ErrorJsonResultException ex)
			{
				if (!retryIfFaild || text == null || ex.JsonResult.errcode != ReturnCode.获取access_token时AppSecret错误或者access_token无效)
				{
					throw;
				}
				AccessTokenResult tokenResult = AccessTokenContainer.GetTokenResult(text, true);
				text2 = tokenResult.access_token;
				result = ApiHandlerWapper.TryCommonApi<T>(fun, text, false);
			}
			return result;
		}
		[Obsolete("请使用TryCommonApi()方法")]
		public static T Do<T>(Func<string, T> fun, string appId, string appSecret, bool retryIfFaild = true) where T : WxJsonResult
		{
			T result = default(T);
			try
			{
				string arg = AccessTokenContainer.TryGetToken(appId, appSecret, false);
				result = fun(arg);
			}
			catch (ErrorJsonResultException ex)
			{
				if (retryIfFaild && ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效)
				{
					string arg = AccessTokenContainer.TryGetToken(appId, appSecret, true);
					result = ApiHandlerWapper.Do<T>(fun, appId, appSecret, false);
				}
			}
			return result;
		}
	}
}
